/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager.create;


import br.com.foxline.atlasmobile.enums.TipoDocumento;
import br.com.foxline.enums.TypeAnnex;
import br.com.foxline.enums.TypeRealty;
import br.com.foxline.model.*;
import br.com.foxline.service.AnnexService;
import br.com.foxline.service.EnderecoService;
import br.com.foxline.service.ImovelService;
import br.com.foxline.service.ProprietarioService;
import br.com.foxline.util.Caracter;
import br.com.foxline.util.Msg;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author laverson
 */
@ManagedBean
@ViewScoped
public class ManagerCreateRealty {

    @EJB
    ImovelService imovelService;
    @EJB
    ProprietarioService proprietarioService;
    @EJB
    EnderecoService enderecoService;
    @EJB
    AnnexService annexService;
    private Imovel imovel;
    private List<TypeRealty> typeRealty;
    private Endereco endereco;
    private int tab = 0;
    private Proprietario owner;
    private Proprietario newOwner;
    private boolean readOnlyAddress;
    private List<Annex> annexs;
    private Annex annex;

    @PostConstruct
    public void init() {
        imovel = new Imovel();
        imovel.setProprietarios(new ArrayList<Proprietario>());
        imovel.setAnnex(new ArrayList<Annex>());
        imovel.setDimensoes(new Dimensao());
        typeRealty = Arrays.asList(TypeRealty.values());
        endereco = new Endereco();
        owner = new Proprietario();
        owner.setTipoDocumento(TipoDocumento.CPF);
        readOnlyAddress = false;
        annexs = new ArrayList<Annex>();
        annex = new Annex();
        initNewOwner();
    }

    public void save() {
        try {
            for (Proprietario prop : imovel.getProprietarios()) {
                if (prop.getId() == null) {
                    proprietarioService.save(prop);
                }
            }
            imovel.setEnderecoImovel(endereco);
            imovel.setAnnex(annexs);
            imovelService.save(imovel);
            init();
            Msg.messagemInfo(Msg.SuccessFull);
        } catch (Exception e) {
        }
    }

    public List<Proprietario> autocompletePeople(String query) {
        if (owner.getTipoDocumento().equals(TipoDocumento.CPF)) {
            return proprietarioService.autocompletePhysical(query);
        }
        return proprietarioService.autocompleteCompany(query);
    }

    public void addOwner() {
        if (imovel.getProprietarios() == null) {
            imovel.setProprietarios(new ArrayList<Proprietario>());
        }
        if (newOwner.getId() != null) {
            newOwner = proprietarioService.find(newOwner.getId());
        }
        imovel.getProprietarios().add(newOwner);
        TipoDocumento typeDoc = owner.getTipoDocumento();
        newOwner = new Proprietario();
        newOwner.setTipoDocumento(typeDoc);
    }

    public void removeOwner(int id) {
        imovel.getProprietarios().remove(id);
    }

    public void cleanOwner() {
        owner = new Proprietario();
    }

    public void saveNewOwner() {
        try {
            newOwner.getEndereco().setCep(Caracter.removecaracter(newOwner.getEndereco().getCep()));
            
            proprietarioService.save(newOwner);
            imovel.getProprietarios().add(newOwner);
            initNewOwner();
            RequestContext.getCurrentInstance().execute("dlg.hide()");
        } catch (Exception e) {
            Msg.messagemError(Msg.Failure);
        }
    }

    private void initNewOwner() {
        newOwner = new Proprietario();
        newOwner.setEndereco(new Endereco());
        newOwner.setTipoDocumento(TipoDocumento.CPF);
    }

    public void existAddress() {
        Endereco a = enderecoService.existCep(newOwner.getEndereco());
        if (a != null) {
            newOwner.setEndereco(a);
        }
    }

    public void existAddressRealty() {
        Endereco a = new Endereco();
        a.setCep(endereco.getCep());
        a = enderecoService.existCep(a);
        if (a != null) {
            endereco.setCep(a.getCep());
            endereco.setLogradouro(a.getLogradouro());
            endereco.setBairro(a.getBairro());
            readOnlyAddress = true;
        } else {
            endereco.setCep(null);
            endereco.setLogradouro(null);
            endereco.setBairro(null);
            endereco.setNumero(null);

            readOnlyAddress = false;
        }
    }

    public void handle(FileUploadEvent event) throws IOException {
        handleAux(event.getFile().getContents(), event.getFile().getFileName(),
                event.getFile().getContentType(), event.getFile().getInputstream());
    }

    private void handleAux(byte[] imageBytes, String nome, String tipo, InputStream is) throws IOException {

        byte[] bytes = null;
        annex = new Annex();
        bytes = imageBytes;
        annex.setType(tipo);
        annex.setDescription(nome);

        if (bytes != null) {
            annex.setFileByte(bytes);
            annex.setType_annex(TypeAnnex.OUTROS);
            annexService.save(annex);
            annexs.add(annex);

            annex = new Annex();

            Msg.messagemInfo("Anexado com Sucesso");
        }
    }

    public void removeAnnex(int a, Annex an) {
        try {
            annexs.remove(a);
            annexService.delete(an);
            Msg.messagemInfo("Documento Excluído");
        } catch (Exception erro) {
            erro.printStackTrace();
        }
    }

    public void closeDialog() {
        newOwner = new Proprietario();
        reinitDialogFields();
        RequestContext.getCurrentInstance().execute("dlg.hide()");
    }

    public void reinitDialogFields() {
        newOwner = new Proprietario();
        newOwner.setEndereco(new Endereco());
        newOwner.setTipoDocumento(TipoDocumento.CPF);
    }

    public List<SelectItem> tipoDocumentoList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (TipoDocumento tipo : TipoDocumento.values()) {
            items.add(new SelectItem(tipo.getTipo(), tipo.getNome()));
        }
        return items;
    }
    
    public void existProprietario() {
        proprietarioService.removeCaracterDocument(newOwner);
        if (newOwner.getTipoDocumento() == TipoDocumento.CPF) {
            if (newOwner.getCpf().equals("")) {
                newOwner = new Proprietario();
                newOwner.setTipoDocumento(TipoDocumento.CPF);
            } else {
                newOwner = proprietarioService.existDocuments(newOwner);
            }
        } else if (newOwner.getTipoDocumento() == TipoDocumento.CNPJ) {
            if (newOwner.getCnpj().equals("")) {
                newOwner = new Proprietario();
                newOwner.setTipoDocumento(TipoDocumento.CNPJ);
            } else {
                newOwner = proprietarioService.existDocuments(newOwner);
            }
        }
    }

    public Imovel getImovel() {
        return imovel;
    }

    public void setImovel(Imovel realty) {
        this.imovel = realty;
    }

    public List<TypeRealty> getTypeRealty() {
        return typeRealty;
    }

    public void setTypeRealty(List<TypeRealty> typeRealty) {
        this.typeRealty = typeRealty;
    }

    public Endereco getEndereco() {
        return endereco;
    }

    public void setEndereco(Endereco endereco) {
        this.endereco = endereco;
    }

    public int getTab() {
        return tab;
    }

    public void setTab(int tab) {
        this.tab = tab;
    }

    public Proprietario getOwner() {
        return owner;
    }

    public void setOwner(Proprietario owner) {
        this.owner = owner;
    }

    public Proprietario getNewOwner() {
        return newOwner;
    }

    public void setNewOwner(Proprietario newOwner) {
        this.newOwner = newOwner;
    }

    public boolean isReadOnlyAddress() {
        return readOnlyAddress;
    }

    public void setReadOnlyAddress(boolean readOnlyAddress) {
        this.readOnlyAddress = readOnlyAddress;
    }

    public Annex getAnnex() {
        return annex;
    }

    public void setAnnex(Annex annex) {
        this.annex = annex;
    }

    public List<Annex> getAnnexs() {
        return annexs;
    }

    public void setAnnexs(List<Annex> annexs) {
        this.annexs = annexs;
    }
}
